package com.jeeplus.modules.guide.web;

import com.google.common.collect.Lists;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.CacheUtils;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.number.RandomUtil;
import com.jeeplus.config.properties.JeePlusProperites;
import com.jeeplus.modules.guide.entity.MobileUser;
import com.jeeplus.modules.guide.service.MobileBusinessService;
import com.jeeplus.modules.guide.service.MobileIndexService;
import com.jeeplus.modules.guide.service.MobileLoginService;
import com.jeeplus.modules.guide.service.VersionService;
import com.jeeplus.modules.guide.task.QueueOther;
import com.jeeplus.modules.guide.task.Send;
import com.jeeplus.modules.guide.utils.*;
import com.jeeplus.modules.sys.entity.*;
import com.jeeplus.modules.sys.security.util.JWTUtil;
import com.jeeplus.modules.sys.service.RoleService;
import com.jeeplus.modules.sys.service.UserService;
import com.jeeplus.modules.sys.utils.RSAUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.tencentcloudapi.sms.v20190711.models.SendStatus;
import lombok.RequiredArgsConstructor;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 全域排号-用户登录/注册Controller
 * @author azj
 * @version 2021-5-15
 */
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/mobileLogin")
public class MobileLoginController {
    private final MobileLoginService mobileLoginService;
    private final RoleService roleService;
    private final UserService userService;
    private final VersionService versionService;
    private final MobileBusinessService mobilebusinessService;
    private final WeixinUtil weixinUtil;
    private final Send send;
    private final QueueOther queueOther;
    private final MobileIndexService mobileIndexService;
    private static final Logger log = LoggerFactory.getLogger(MobileLoginController.class);
    //接口AppKeyValue
    @Value("${AppKeyValue}")
    private String AppKeyValue;
    @Value("${faceStreetUrl}")
    private String faceStreetUrl;
    //微信AppID
    @Value("${AppID}")
    private String AppID;
    //微信AppSecret
    @Value("${AppSecret}")
    private String AppSecret;
    //注册基础信息
    @Value("${pwd}")
    private String pwd;
    @Value("${roleId}")
    private String roleId;
    @Value("${companyId}")
    private String companyId;
    @Value("${companyName}")
    private String companyName;
    @Value("${officeId}")
    private String officeId;
    @Value("${officeName}")
    private String officeName;
    @Value("${faceUrl}")
    private String faceUrl;
    @Value("${faceUrlFR}")
    private String faceUrlFR;
    @Value("${bindUrlFR}")
    private String bindUrlFR;
    @Value("${bindUrlFRRZ}")
    private String bindUrlFRRZ;
    //人脸验证第三方key
    @Value("${appkey}")
    private String appkey;
    //人脸验证第三方信息绑定
    @Value("${faceBindUrl}")
    private String faceBindUrl;
    //人脸验证第三方用户信息
    @Value("${faceUserUrl}")
    private String faceUserUrl;
    //人脸验证第三方用户信息注册
    @Value("${userUrl}")
    private String userUrl;
    //第三方用户验证
    @Value("${checkUser}")
    private String checkUser;
    //手机端获取微信id
    @Value("${toCodeUrl}")
    private String toCodeUrl;
    //二维码地址
    @Value("${qrUrl}")
    private String qrUrl;
    //默认手机头像
    @Value("${userImg}")
    private String userImg;
    //腾讯云 SecretId
    @Value("${SecretId}")
    private String SecretId;
    //腾讯云 SecretKey
    @Value("${SecretKey}")
    private String SecretKey;
    //蓉易办-单点登录-密匙
    @Value("${TFRYB_KEY}")
    private String TFRYB_KEY;
    //天府通办-单点登录-密匙
    @Value("${TFTB_KEY}")
    private String TFTB_KEY;
    //高馨办默认注册跳转地址
    @Value("${pageUrl}")
    private String pageUrl;
    //获取人脸验证url第三方 后台传身份信息验证 认证后跳转至账号绑定页面 一码办成事
    @Value("${bindUrlNoValue}")
    private String bindUrlNoValue;
    //获取人脸验证url第三方 后台传身份信息验证 认证后跳转至账号绑定页面 个人中心
    @Value("${bindUrlNoValueUser}")
    private String bindUrlNoValueUser;
    //获取人脸验证url第三方 后台传身份信息验证 认证后跳转至账号绑定页面 首页
    @Value("${bindUrlNoValueIndex}")
    private String bindUrlNoValueIndex;
    //#人才调用url获取code
    @Value("${rcCodeUrl}")
    private String rcCodeUrl;
    //#人才单点对接跳转事项办事指南url
    @Value("${rcBSZNUrl}")
    private String rcBSZNUrl;
    //获取人脸验证url第三方 后台传身份信息验证 认证后跳转至自助取件认证成功界面
    @Value("${bindUrlNoValueQR}")
    private String bindUrlNoValueQR;


    public static final String VERIFICATION_CODE_CACHE = "verificationCodeCache";
    public static final String TOKEN_CACHE = "tokenCache";

    /**
     * 微信加载跳转页 获取code
     * wxurl 需要跳转的url
     */
    @GetMapping(value = "toCode")
    public void toCode(HttpServletResponse response, String code, @RequestParam(required = false) String wxurl, HttpServletRequest request) {
        if (StringUtils.isNotBlank(code)) {
            //页面有code参数 跳转至 获取openid
            loginOpendId(code, wxurl, response);
        } else {
            try {
                //页面无code参数 跳转至 获取code 用于获取openid
                String url = WeiXinConfig.getCodeUrl;
                url = url.replace("$appid", AppID).replace(
                        "$redirect_uri", toCodeUrl + "?wxurl=" + wxurl);
                response.sendRedirect(url);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 微信加载跳转页 获取OpendId 并实现注册 自动登录操作
     */
    public void loginOpendId(String code, String wxurl, HttpServletResponse response) {
        // 获取openid请求
        String url = WeiXinConfig.getOpenId;
        String qjQR = "";
        // 参数替换
        // 处理 # 号问题
        wxurl = wxurl.replace("/wx/","/#/").replace("$$","&");
        String wxUrl = "appid=AppId&secret=AppSecret&code=CODE&grant_type=authorization_code"
                .replace("AppId", AppID).replace("AppSecret", AppSecret).replace("CODE", code);
        // 获取微信用户opendid
        String openid = JsonObjectUtils.getJsonValue(HttpRequestUtil.sendPost(url, wxUrl),"openid");
        if(null != openid && StringUtils.isNotBlank(openid)){
            if(wxurl.indexOf("qjQR") >= 0){
                //对接取件柜 获取扫码标识 appraiseQJ?qr= 填充用户信息
                String[] split = wxurl.split("&");
                for(String str : split){
                    if(str.indexOf("qjQR") >=0){
                        qjQR = str.substring(str.indexOf("=")+1,str.length());
                        //二维码已使用
                        if(userService.findCountQR(qjQR) >= 1){
                            try{
                                url = bindUrlNoValueQR + "?appraiseStatus=4";
                                response.sendRedirect(url);
                            }catch (Exception e){
                                log.error("微信用户登录失败："+e.getMessage());
                            }
                        }else{
                            userService.intoQJQR(qjQR,openid);
                        }
                    }
                }
            }
            Map<String, Object> map = mobileLoginService.selectUser(openid);
            if (map != null && map.containsKey("tell") && StringUtils.isNotBlank(map.get("tell").toString())) {
                //登录
                User user = UserUtils.getByLoginName(openid);
                String urls = WeiXinConfig.weixin_user_info.replace("OPENID", openid).replace("ACCESS_TOKEN", String.valueOf(CacheUtils.get(TOKEN_CACHE, "token")));
                String headimgurl = JsonObjectUtils.getJsonValue(HttpRequestUtil.sendPost(urls, null),"headimgurl");
                if(null != headimgurl && StringUtils.isNotBlank(headimgurl)){
                    headimgurl = headimgurl.replace("http","https");
                    user.setPhoto(headimgurl);
                    userService.updateUserInfo(user);
                }
                if (user != null && UserService.validatePassword(pwd, user.getPassword())) {
                    if (!(JeePlusProperites.NO.equals(user.getLoginFlag()))) {
                        String token = JWTUtil.createAccessToken(openid, user.getPassword());
                        String refreshToken = JWTUtil.createRefreshToken(openid, user.getPassword());
                        String uuid = UUID.randomUUID().toString();
                        if(wxurl.indexOf("checkQR") >= 0){
                            uuid = wxurl.split("=")[1];
                            wxurl += "&openid="+openid;
                        }else{
                            wxurl += "&uuid=" + uuid+"&openid="+openid;
                        }
                        mobileLoginService.intoUserToken(uuid,token,openid);
                        try{
                            //判断是否为扫码验证
                            if(StringUtils.isNotBlank(qjQR)){
                                wxurl += "&iszc="+true;
                            }
                            //重定向前端页面
                            response.sendRedirect(wxurl);
                        }catch (Exception e){
                            log.error("微信用户登录失败："+e.getMessage());
                        }
                    }
                }
            }else{
                try{
                    //重定向前端页面
                    wxurl += "&login=login&openid=" +openid;
                    response.sendRedirect(wxurl);
                }catch (Exception e){
                    log.error("微信用户登录失败："+e.getMessage());
                }
            }
        }
    }
    /**
     * 发送注册验证码
     * tell手机号
     */
    @GetMapping("sendSmsCheck")
    public AjaxJson sendSmsCheck(@RequestParam(required = false) String tell) {
        if(mobileLoginService.findUserTell(tell) >= 1){
            return AjaxJson.error("该手机号已在高馨办注册，请前往高馨办网上取号！");
        }
        String verificationCode = String.valueOf(RandomUtil.nextInt(100000, 999999));
        try {
            //发送短信
            send.sendSmsVerificationCode(tell,verificationCode);
            CacheUtils.put(VERIFICATION_CODE_CACHE, tell, verificationCode);
            log.error("tell:"+tell+"&code:"+verificationCode);
            return AjaxJson.success("发送成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxJson.error("短信发送异常!" + e.getMessage());
        }

    }

    /**
     * 生成二维码
     *
     * @throws Exception
     */
    @PostMapping("createTellCode")
    public AjaxJson createTellCode(String tell,String code) {
        Object cacheInfo = CacheUtils.get(VERIFICATION_CODE_CACHE, tell);
        if (null == cacheInfo) {
            return AjaxJson.error("验证码失效！");
        } else {
            if (cacheInfo.toString().equalsIgnoreCase(code)) {
                CacheUtils.remove(VERIFICATION_CODE_CACHE, tell);
                if(mobileLoginService.findUserValue(tell) >= 1 || mobileLoginService.findUserValueMonth(tell) >= 4){
                    return AjaxJson.error("该手机取号已上限！");
                }
                String uuid = "gxls"+UUID.randomUUID().toString();
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    userService.insertQR(uuid,sdf.format(new Date()),600,"oyyT9s8WTu-wfSt3ZX2QSnC6FbbU",tell);
                    return AjaxJson.success("二维码生成成功").put("path", qrUrl + uuid).put("loseTime",300);
                } catch (Exception e) {
                    log.error("二维码生成失败:"+e.getMessage());
                    return AjaxJson.error("二维码生成失败");
                }
            }
            CacheUtils.remove(VERIFICATION_CODE_CACHE, tell);
            return AjaxJson.error("验证码失效！");
        }
    }

    /**
     * 发送注册验证码
     * openid用户微信id
     * tell手机号
     */
    @GetMapping("sendSmsVerificationCode")
    public AjaxJson sendSmsVerificationCode(@RequestParam(required = false) String openid, @RequestParam(required = false) String tell) {
        tell = new String(Base64.decodeBase64(tell));
        Integer result = userService.getUserPhone(tell);
        if(result != 0){
            return AjaxJson.error("该手机号已注册!");
        }
        String verificationCode = String.valueOf(RandomUtil.nextInt(100000, 999999));
        SendStatus sendStatus = null;//发送注册验证码
        try {
            //发送短信
            send.sendSmsVerificationCode(tell,verificationCode);
            String cache_key = openid + "-" + tell;
            CacheUtils.put(VERIFICATION_CODE_CACHE, cache_key, verificationCode);
            log.error("tell:"+tell+"&code:"+verificationCode);
            return AjaxJson.success("发送成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxJson.error("短信发送异常!" + e.getMessage());
        }

    }

    /**
     * 发送认证注册验证码
     * openid用户微信id
     * tell手机号
     */
    @GetMapping("sendRZ")
    public AjaxJson sendRZ(@RequestParam(required = false) String openid, @RequestParam(required = false) String tell) {
        tell = new String(Base64.decodeBase64(tell));
        String verificationCode = String.valueOf(RandomUtil.nextInt(100000, 999999));
        SendStatus sendStatus = null;//发送注册验证码
        try {
            //发送短信
            send.sendSmsVerificationCode(tell,verificationCode);
            String cache_key = openid + "-" + tell;
            CacheUtils.put(VERIFICATION_CODE_CACHE, cache_key, verificationCode);
            log.error("tell:"+tell+"&code:"+verificationCode);
            return AjaxJson.success("发送成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxJson.error("短信发送异常!" + e.getMessage());
        }

    }

    /**
     * 发送修改验证码
     * openid用户微信id
     * tell手机号
     */
    @GetMapping("sendSmsUpdateCode")
    public AjaxJson sendSmsUpdateCode(@RequestParam(required = false) String openid, @RequestParam(required = false) String tell) {
        tell = new String(Base64.decodeBase64(tell));
        String verificationCode = String.valueOf(RandomUtil.nextInt(100000, 999999));
        SendStatus sendStatus = null;//发送注册验证码
        try {
            //发送短信
            send.sendSmsVerificationCode(tell,verificationCode);
            String cache_key = openid + "-" + tell;
            CacheUtils.put(VERIFICATION_CODE_CACHE, cache_key, verificationCode);
            log.error("tell:"+tell+"&code:"+verificationCode);
            return AjaxJson.success("发送成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxJson.error("短信发送异常!" + e.getMessage());
        }

    }

    /**
     * 第三方公司注册
     *蓉易办-单点登录-密匙
     *天府通办-单点登录-密匙
     */
    @RequestMapping(value = "/saveUserByRYB", method = RequestMethod.POST)
    public AjaxJson saveUserByRYB(String userName,String idCard,String tel,String jwtToken,String uuid,String type,String isRYB,String deptName,String deptCode,String socialCreditCode) throws Exception {
        //type 10为法人信息  20为个人  isRYB 1是  0否
        Map<String,String> map=new HashMap<>();
        String area = "";
        if ("1".equals(isRYB)){
            area = "蓉易办";
            map=jieMiRYB(userName,idCard,tel,jwtToken,uuid,type,isRYB,deptName,deptCode,socialCreditCode);
        }else {
            area = "天府通办";
            map=jieMiTFTB(userName,idCard,tel,jwtToken,uuid,type,isRYB,deptName,deptCode,socialCreditCode);
        }
        User users = UserUtils.getByLoginNameNow(map.get("tel"));
        if (users != null && UserService.validatePassword(pwd, users.getPassword())) {
            if (!(JeePlusProperites.NO.equals(users.getLoginFlag()))) {
                return AjaxJson.success("注册成功！").put("token",JWTUtil.createAccessToken(map.get("tel"), users.getPassword()));
            }
        }else{
            users = new User();
            Office of = new Office();
            List<String> roleIdList = new ArrayList<String>();
            roleIdList.add(roleId);
            of.setId(officeId);
            of.setName(officeName);
            Office company = new Office();
            company.setId(companyId);
            company.setName(companyName);
            users.setPassword(pwd);
            users.setLoginFlag("1");
            users.setDelFlag("0");
            users.setOffice(of);
            users.setCompany(company);
            users.setPhone(map.get("tel"));
            users.setRoleIdList(roleIdList);
            //注册
            users.setNo("0000");
            users.setPassword(userService.entryptPassword(users.getPassword()));
            users.setName(map.get("userName"));
            users.setAddress("暂无");
            users.setLoginName(map.get("tel"));
            users.setPhoto(userImg);
            // 角色数据有效性验证，过滤不在授权内的角色
            List<Role> roleList = Lists.newArrayList();
            for (String roleId : roleIdList) {
                roleList.add(roleService.get(roleId));
            }
            users.setRoleList(roleList);
            // 保存用户信息
            try {
                mobileLoginService.intoOtherAllValue("暂无",map.get("idCard"),map.get("userName"),area,map.get("tel"),map.get("tel"),"");
                userService.saveUser(users);
                return AjaxJson.success("注册成功！").put("token",JWTUtil.createAccessToken(users.getPhone(), users.getPassword()));
            }catch (Exception e){
                log.error("蓉易办、天府通办登录:"+e.getMessage());
            }
        }
        return AjaxJson.error("注册失败！").put("code",400);
    }


    /**
     * 第三方公司注册
     *融媒体
     *
     */
    @RequestMapping(value = "/saveUserByRMT", method = RequestMethod.POST)
    public AjaxJson saveUserByRMT(@RequestHeader("AppKey") String AppKey,String userName,String idCard,String tell) {
        if (!AppKeyValue.equals(AppKey)) return AjaxJson.error("AppKey is error!").put("code", 400);
        User users = UserUtils.getByLoginNameNow(userService.findLoginName(tell));
        String uuid = UUID.randomUUID().toString();
        if (users != null && UserService.validatePassword(pwd, users.getPassword())) {
            if (!(JeePlusProperites.NO.equals(users.getLoginFlag()))) {
                mobileLoginService.intoUserToken(uuid,JWTUtil.createAccessToken(tell, users.getPassword()),tell);
                return AjaxJson.success("注册成功！").put("uuid",uuid);
            }
        }else{
            users = new User();
            Office of = new Office();
            List<String> roleIdList = new ArrayList<String>();
            roleIdList.add(roleId);
            of.setId(officeId);
            of.setName(officeName);
            Office company = new Office();
            company.setId(companyId);
            company.setName(companyName);
            users.setPassword(pwd);
            users.setLoginFlag("1");
            users.setDelFlag("0");
            users.setOffice(of);
            users.setCompany(company);
            users.setPhone(tell);
            users.setRoleIdList(roleIdList);
            //注册
            users.setNo("0000");
            users.setPassword(userService.entryptPassword(users.getPassword()));
            users.setName(userName);
            users.setAddress("暂无");
            users.setLoginName(tell);
            users.setPhoto(userImg);
            // 角色数据有效性验证，过滤不在授权内的角色
            List<Role> roleList = Lists.newArrayList();
            for (String roleId : roleIdList) {
                roleList.add(roleService.get(roleId));
            }
            users.setRoleList(roleList);
            // 保存用户信息
            try {
                mobileLoginService.intoOtherAllValue("暂无",idCard,userName,"融媒体",tell,tell,"");
                userService.saveUser(users);
                mobileLoginService.intoUserToken(uuid,JWTUtil.createAccessToken(users.getPhone(), users.getPassword()),tell);
                return AjaxJson.success("注册成功！").put("uuid",uuid);
            }catch (Exception e){
                log.error("融媒体登录:"+e.getMessage());
            }
        }
        return AjaxJson.error("注册失败！").put("code",400);
    }

    /**
     * 第三方公司注册
     * 新川
     *
     */
    @RequestMapping(value = "/saveUserByXC", method = RequestMethod.POST)
    public AjaxJson saveUserByXC(@RequestHeader("AppKey") String AppKey,String userName,String idCard,String tell) {
        if (!AppKeyValue.equals(AppKey)) return AjaxJson.error("AppKey is error!").put("code", 400);
        User users = UserUtils.getByLoginNameNow(userService.findLoginName(tell));
        String uuid = UUID.randomUUID().toString();
        if (users != null && UserService.validatePassword(pwd, users.getPassword())) {
            if (!(JeePlusProperites.NO.equals(users.getLoginFlag()))) {
                mobileLoginService.intoUserToken(uuid,JWTUtil.createAccessToken(tell, users.getPassword()),tell);
                return AjaxJson.success("注册成功！").put("uuid",uuid);
            }
        }else{
            users = new User();
            Office of = new Office();
            List<String> roleIdList = new ArrayList<String>();
            roleIdList.add(roleId);
            of.setId(officeId);
            of.setName(officeName);
            Office company = new Office();
            company.setId(companyId);
            company.setName(companyName);
            users.setPassword(pwd);
            users.setLoginFlag("1");
            users.setDelFlag("0");
            users.setOffice(of);
            users.setCompany(company);
            users.setPhone(tell);
            users.setRoleIdList(roleIdList);
            //注册
            users.setNo("0000");
            users.setPassword(userService.entryptPassword(users.getPassword()));
            users.setName(userName);
            users.setAddress("暂无");
            users.setLoginName(tell);
            users.setPhoto(userImg);
            // 角色数据有效性验证，过滤不在授权内的角色
            List<Role> roleList = Lists.newArrayList();
            for (String roleId : roleIdList) {
                roleList.add(roleService.get(roleId));
            }
            users.setRoleList(roleList);
            // 保存用户信息
            try {
                mobileLoginService.intoOtherAllValue("暂无",idCard,userName,"新川",tell,tell,"");
                userService.saveUser(users);
                mobileLoginService.intoUserToken(uuid,JWTUtil.createAccessToken(users.getPhone(), users.getPassword()),tell);
                return AjaxJson.success("注册成功！").put("uuid",uuid);
            }catch (Exception e){
                log.error("融媒体登录:"+e.getMessage());
            }
        }
        return AjaxJson.error("注册失败！").put("code",400);
    }

    /**
     * 第三方公司注册
     *人才 单点对接及办事指南跳转
     *
     */
    @RequestMapping(value = "/saveUserByRC", method = RequestMethod.POST)
    public AjaxJson saveUserByRC(@RequestHeader("AppKey") String AppKey,String userName,String idCard,String tell,String oid,HttpServletRequest request) {
        String  publicIp = UserUtils.getClientIpAddress(request);
        if(userService.checkUserIp(publicIp) <= 0){
            return AjaxJson.error("拒绝访问，非法ip:"+publicIp).put("code", 400);
        }
        if (!AppKeyValue.equals(AppKey)) return AjaxJson.error("AppKey is error!").put("code", 400);
        User users = UserUtils.getByLoginNameNow(userService.findLoginName(tell));
        String uuid = UUID.randomUUID().toString();
        if (users != null && UserService.validatePassword(pwd, users.getPassword())) {
            if (!(JeePlusProperites.NO.equals(users.getLoginFlag()))) {
                mobileLoginService.intoUserToken(uuid,JWTUtil.createAccessToken(tell, users.getPassword()),tell);
                return AjaxJson.success("操作成功！").put("url",rcBSZNUrl+"&uuid="+uuid+"&oid="+oid);
            }
        }else{
            users = new User();
            Office of = new Office();
            List<String> roleIdList = new ArrayList<String>();
            roleIdList.add(roleId);
            of.setId(officeId);
            of.setName(officeName);
            Office company = new Office();
            company.setId(companyId);
            company.setName(companyName);
            users.setPassword(pwd);
            users.setLoginFlag("1");
            users.setDelFlag("0");
            users.setOffice(of);
            users.setCompany(company);
            users.setPhone(tell);
            users.setRoleIdList(roleIdList);
            //注册
            users.setNo("0000");
            users.setPassword(userService.entryptPassword(users.getPassword()));
            users.setName(userName);
            users.setAddress("暂无");
            users.setLoginName(tell);
            users.setPhoto(userImg);
            // 角色数据有效性验证，过滤不在授权内的角色
            List<Role> roleList = Lists.newArrayList();
            for (String roleId : roleIdList) {
                roleList.add(roleService.get(roleId));
            }
            users.setRoleList(roleList);
            // 保存用户信息
            try {
                mobileLoginService.intoOtherAllValue("暂无",idCard,userName,"人才服务",tell,tell,"");
                userService.saveUser(users);
                mobileLoginService.intoUserToken(uuid,JWTUtil.createAccessToken(users.getPhone(), users.getPassword()),tell);
                return AjaxJson.success("操作成功！").put("url",rcBSZNUrl+"&uuid="+uuid+"&oid="+oid);
            }catch (Exception e){
                log.error("融媒体登录:"+e.getMessage());
            }
        }
        return AjaxJson.error("注册失败！").put("code",400);
    }

        /**
         * 验证并保存用户信息
         * openid用户微信id
         * tell联系电话
         * username用户昵称
         * address地址
         * 跳转url
         */
    @PostMapping("saveUserInfo")
    public AjaxJson saveUserInfo(@RequestParam(required = false) String openid, @RequestParam(required = false) String tell, @RequestParam(required = false) String username, @RequestParam(required = false) String code, @RequestParam(required = false) String address,@RequestParam(required = false) String url) {
        tell = new String(Base64.decodeBase64(tell));
        String cache_key = openid + "-" + tell;
        Object cacheInfo = CacheUtils.get(VERIFICATION_CODE_CACHE, cache_key);
        if (null == cacheInfo) {
            return AjaxJson.error("验证失效！");
        } else {
            if (cacheInfo.toString().equalsIgnoreCase(code)) {
                //填写基本数据
                synchronized (this){
                    User users = UserUtils.getByLoginNameNow(openid);
                    if(users != null && openid.equals(users.getLoginName())){
                        return AjaxJson.error("");
                    }else{
                        users = UserUtils.getByLoginNameCache(openid);
                        if(users == null){
                            users = new User();
                        }
                        Office of = new Office();
                        List<String> roleIdList = new ArrayList<String>();
                        roleIdList.add(roleId);
                        of.setId(officeId);
                        of.setName(officeName);
                        Office company = new Office();
                        company.setId(companyId);
                        company.setName(companyName);
                        users.setPassword(pwd);
                        //禁止登录
                        users.setLoginFlag("0");
                        //无效
                        users.setDelFlag("1");
                        users.setOffice(of);
                        users.setCompany(company);
                        users.setPhone(tell);
                        users.setRoleIdList(roleIdList);
                        //获取微信用户信息
                        String wxToken = String.valueOf(CacheUtils.get(TOKEN_CACHE, "token"));
                        String urls = WeiXinConfig.weixin_user_info.replace("OPENID", openid).replace("ACCESS_TOKEN", wxToken);
                        String headimgurl = "";
                        JSONObject jsonUser = null;
                        try {
                            jsonUser = JSONObject.fromObject(HttpRequestUtil.sendPost(urls, null));
                            if(jsonUser != null && null != jsonUser.get("headimgurl")){
                                headimgurl = jsonUser.getString("headimgurl");
                                headimgurl = headimgurl.replace("http","https");
                            }else{
                                headimgurl = userImg;
                            }
                        }catch (Exception e){
                            headimgurl = userImg;
                            log.error(e.getMessage());
                            e.printStackTrace();
                        }
                        //注册
                        users.setNo("0000");
                        users.setPassword(userService.entryptPassword(users.getPassword()));
                        users.setName(username);
                        users.setAddress(address);
                        users.setLoginName(openid);
                        users.setPhoto(headimgurl);
                        // 角色数据有效性验证，过滤不在授权内的角色
                        List<Role> roleList = Lists.newArrayList();
                        for (String roleId : roleIdList) {
                            roleList.add(roleService.get(roleId));
                        }
                        users.setRoleList(roleList);
                        // 保存用户信息
                        userService.saveUser(users);
                        String result = null;
                        try{
                            // 查询是否已注册第三方
                            result = HttpRequestUtil.checkUser(checkUser+tell,appkey);
                            if(null != result && result.length() >= 10){
                                // 同步第三方用户数据
                                jsonUser = JSONArray.fromObject(result).getJSONObject(0);
                                userService.saveUserOther(openid,jsonUser.getString("id"),tell,url);
                                return AjaxJson.success("提交成功！");
                            }else{
                                // 注册第三方用户数据
                                result = "name="+username+"&identifier="+tell+"&phone="+tell+"&openid="+openid;
                                log.error("用户注册请求参数："+result);
                                result = HttpRequestUtil.getUser(result,userUrl,appkey);
                                if(null == result){
                                    log.error("注册第三用户数据失败！result:"+result);
                                    return AjaxJson.error("注册第三用户数据失败");
                                }else{
                                    jsonUser = JSONObject.fromObject(result);
                                    userService.saveUserOther(openid,jsonUser.getString("id"),tell,url);
                                    return AjaxJson.success("提交成功！");
                                }
                            }
                        }catch (Exception e){
                            log.error("添加本地第三用户数据失败！注册第三方结果:"+result+"；error:"+e.getMessage());
                            return AjaxJson.error("注册第三用户数据失败");
                        }
                    }
                }
            } else {
                return AjaxJson.error("验证错误！");
            }
        }
    }

    /**
     * 获取人脸验证url
     * openid用户微信id
     */
    @GetMapping("getFaceUrl")
    public AjaxJson getFaceUrl(String openid) {
        String message = HttpRequestUtil.sendGet(faceUrl+openid,appkey);
        log.error("getFaceUrl:" + message);
        if (message == null) {
            log.error("获取人脸验证url失败！" + message);
            return AjaxJson.error("获取人脸验证url失败！" + message);
        } else {
            JSONObject obj = JSONObject.fromObject(message);
            System.out.println(message);
            if (StringUtils.isNotBlank(obj.getString("identity_vertify_url"))) {
                return AjaxJson.success().put("url", obj.getString("identity_vertify_url"));
            } else {
                log.error("获取人脸验证url失败！" + message);
                return AjaxJson.error("获取人脸验证url失败！" + message);
            }
        }
    }

    /**
     * 获取街道人脸验证url
     * openid用户微信id
     */
    @GetMapping("getStreetFaceUrl")
    public String getStreetFaceUrl(String url) {
        return HttpRequestUtil.sendGet(faceStreetUrl+url,appkey);
    }

    /**
     * 获取法人人脸验证url
     */
    @GetMapping("getFaceUrlFR")
    public AjaxJson getFaceUrlFR(String openid) {
        String message = CheckFace.getCheckFaceUrl(SecretId, SecretKey, faceUrlFR+openid);
        log.error("getFaceUrlFR:" + message);
        if (message == null) {
            return AjaxJson.error("获取人脸验证url失败！" + message);
        } else {
            JSONObject obj = JSONObject.fromObject(message);
            if (StringUtils.isNotBlank(obj.getString("Url"))) {
                return AjaxJson.success().put("url", obj.getString("Url"));
            } else {
                log.error("获取人脸验证url失败！" + message);
                return AjaxJson.error("获取人脸验证url失败！" + message);
            }
        }
    }

    /**
     * 获取人脸验证url
     * 融媒体对接
     */
    @GetMapping("getFaceUrlRMT")
    public AjaxJson getFaceUrlRMT(@RequestHeader("AppKey") String AppKey,String url) {
        if (!AppKeyValue.equals(AppKey)) return AjaxJson.error("AppKey is error!").put("code", 400);
        String message = CheckFace.getCheckFaceUrl(SecretId, SecretKey, url);
        log.error("getFaceUrlRMT:" + message);
        if (message == null) {
            return AjaxJson.error("获取人脸验证url失败！" + message);
        } else {
            JSONObject obj = JSONObject.fromObject(message);
            if (org.apache.commons.lang.StringUtils.isNotBlank(obj.getString("Url"))) {
                return AjaxJson.success().put("url", obj.getString("Url"));
            } else {
                log.error("融媒体获取人脸验证url失败！" + message);
                return AjaxJson.error("获取人脸验证url失败！" + message);
            }
        }

    }

    /**
     * 获取人脸验证url
     * 融媒体对接
     */
    @GetMapping("getFaceValueRMT")
    public AjaxJson getFaceValueRMT(@RequestHeader("AppKey") String AppKey,String BizToken) {
        if (!AppKeyValue.equals(AppKey)) return AjaxJson.error("AppKey is error!").put("code", 400);
        return AjaxJson.success().put("data", JSONObject.fromObject(CheckFace.GetDetectOnlyInfo(SecretId, SecretKey, BizToken)));
    }



    /**
     * 获取人脸验证并保存
     * openid用户微信id
     * BizToken验证码
     */
    @RequestMapping(value = "/getFaceResultFR/{openid}", method = RequestMethod.GET)
    public void getFaceResultFR(@PathVariable String openid,String BizToken, HttpServletResponse response){
        try{
            //企业信息保存
            StringBuilder sb = new StringBuilder();
            //个人认证企业 获取个人数据 判断是个人升级认证企业还是注册企业流程
            Map <String, String> rzResult = mobileLoginService.findUser(openid);
            //验证企业有效性
            Map <String, String> map = mobileLoginService.findCompanyValue(openid);
            //用户注册数据
            User users = UserUtils.getByLoginNameCache(openid);
            if(rzResult == null){
                //企业注册 获取身份证详情  前端需上传身份证照片
                sb.append(CheckFace.GetDetectInfo(SecretId, SecretKey, BizToken));
                JSONObject obj = JSONObject.fromObject(sb.toString());
                obj = JSONObject.fromObject(obj.get("DetectInfo"));
                JSONObject objIdcard = JSONObject.fromObject(obj.get("IdCardData"));
                obj = JSONObject.fromObject(obj.get("Text"));
                if(null != map && map.get("idcard").equals(obj.getString("OcrIdCard"))){
                    //更新法人信息
                    userService.updatelegalUserImg(map.get("companyName"),objIdcard.getString("OcrBack"),objIdcard.getString("OcrFront"),obj.getString("IdCard"),BizToken,openid);
                    //法人信息注册账号
                    MobileUser mu = mobileLoginService.findUserMatter(openid);
                    if(StringUtils.isBlank(mu.getUrl()))mu.setUrl(pageUrl);
                    users.setLoginFlag("1");
                    users.setDelFlag("0");
                    try{
                        queueOther.toFileOcrBackFR(objIdcard.getString("OcrBack"),openid);
                        queueOther.toFileOcrFrontFR(objIdcard.getString("OcrFront"),openid);
                        mu.setOcrBack("暂不下载");
                        mu.setOcrFront("暂不下载");
                        mu.setIdcard(obj.getString("OcrIdCard"));
                        mu.setAddress(obj.getString("OcrAddress"));
                        mu.setName(obj.getString("OcrName"));
                        mu.setLoginName(openid);
                        mu.setBizToken(BizToken);
                        int flag = mobileLoginService.updateUserMatter(mu,users);
                        if(flag <= 0){
                            log.error("保存第三方用户失败！" + mu.toString());
                        }
                        queueOther.updateUserMaterialHistory(openid);
                        if (users != null && UserService.validatePassword(pwd, users.getPassword())) {
                            if (!(JeePlusProperites.NO.equals(users.getLoginFlag()))) {
                                String token = JWTUtil.createAccessToken(openid, users.getPassword());
                                String wxurl = mu.getUrl();
                                wxurl = wxurl.replace("/wx/","/#/").replace("$$","&");
                                String uuid = UUID.randomUUID().toString();
                                mobileLoginService.intoUserToken(uuid,token,openid);
                                wxurl += "&uuid=" + uuid;
                                response.sendRedirect(wxurl);
                            }
                        }
                    }catch (Exception e){
                        log.error("保存用户失败！" + e.getMessage());
                    }
                    response.sendRedirect(bindUrlFR+"?openid="+openid+"&login=login&bindType=false");
                }else{
                    //企业验证失败
                    response.sendRedirect(bindUrlFR+"?openid="+openid+"&login=login&check=false");
                }
            }else{
                //个人升级认证企业 获取身份证详情  后端需上传身份证信息
                sb.append(CheckFace.GetDetectInfoTextAll(SecretId, SecretKey, BizToken));
                JSONObject obj = JSONObject.fromObject(sb.toString());
                obj = JSONObject.fromObject(obj.get("DetectInfo"));
                obj = obj.getJSONObject("Text");
                if(null != map && map.get("idcard").equals(obj.getString("IdCard"))){
                    //更新法人信息
                    userService.updatelegalUserImg(map.get("companyName"),"","",obj.getString("IdCard"),BizToken,openid);
                    if (users != null && UserService.validatePassword(pwd, users.getPassword())) {
                        if (!(JeePlusProperites.NO.equals(users.getLoginFlag()))) {
                            String token = JWTUtil.createAccessToken(openid, users.getPassword());
                            String uuid = UUID.randomUUID().toString();
                            mobileLoginService.intoUserToken(uuid,token,openid);
                            response.sendRedirect(bindUrlFRRZ+"?check=true&uuid=" + uuid);
                        }
                    }
                }else{
                    //企业验证失败 且实现个人注册
                    if (users != null && UserService.validatePassword(pwd, users.getPassword())) {
                        if (!(JeePlusProperites.NO.equals(users.getLoginFlag()))) {
                            String token = JWTUtil.createAccessToken(openid, users.getPassword());
                            String uuid = UUID.randomUUID().toString();
                            mobileLoginService.intoUserToken(uuid,token,openid);
                            response.sendRedirect(bindUrlFRRZ+"?check=false&uuid=" + uuid);
                        }
                    }
                }
            }
        }catch (Exception e){
            log.error(openid+"法人:"+e.getMessage());
        }
    }

    /**
     * 获取人脸验证并保存 后台传材料认证 一码办成事
     * openid用户微信id
     * BizToken验证码
     */
    @RequestMapping(value = "/getFaceResultNoValue/{openid}", method = RequestMethod.GET)
    public void getFaceResultNoValue(@PathVariable String openid,String BizToken, HttpServletResponse response){
        try{
            User users = UserUtils.getByLoginNameCache(openid);
            if (users != null && UserService.validatePassword(pwd, users.getPassword())) {
                if (!(JeePlusProperites.NO.equals(users.getLoginFlag()))) {
                    String token = JWTUtil.createAccessToken(openid, users.getPassword());
                    String uuid = UUID.randomUUID().toString();
                    //记录token
                    mobileLoginService.intoUserToken(uuid,token,openid);
                    //记录人脸验证
                    String result = CheckFace.GetDetectInfoText(SecretId, SecretKey, BizToken);
                    if(null != result && !"".equals(result)){
                        JSONObject obj = JSONObject.fromObject(result);
                        obj = JSONObject.fromObject(obj.get("DetectInfo"));
                        if("成功".equals(obj.getJSONObject("Text").getString("ErrMsg"))){
                            userService.intoUserCheck(openid,BizToken);
                        }
                    }
                    String url = bindUrlNoValue + "?uuid=" + uuid;
                    response.sendRedirect(url);
                }
            }
        }catch (Exception e){
            log.error(openid+"法人:"+e.getMessage());
        }
    }

    /**
     * 获取人脸验证并保存 后台传材料认证 自助取件柜人脸验证页面 跳转业务处理 验证是否真实有效
     * openid用户微信id
     * BizToken验证码
     */
    @RequestMapping(value = "/getFaceResultNoValueQR/{openid}", method = RequestMethod.GET)
    public void getFaceResultNoValueQR(@PathVariable String openid,String BizToken, HttpServletResponse response){
        try{
            User users = UserUtils.getByLoginNameCache(openid);
            if (users != null && UserService.validatePassword(pwd, users.getPassword())) {
                if (!(JeePlusProperites.NO.equals(users.getLoginFlag()))) {
                    String token = JWTUtil.createAccessToken(openid, users.getPassword());
                    String uuid = UUID.randomUUID().toString();
                    //记录token
                    mobileLoginService.intoUserToken(uuid,token,openid);
                    //记录人脸验证
                    String result = CheckFace.GetDetectInfoText(SecretId, SecretKey, BizToken);
                    if(null != result && !"".equals(result)){
                        JSONObject obj = JSONObject.fromObject(result);
                        obj = JSONObject.fromObject(obj.get("DetectInfo"));
                        if("成功".equals(obj.getJSONObject("Text").getString("ErrMsg"))){
                            userService.intoUserCheck(openid,BizToken);
                            userService.updateQJQRStatus(openid);
                            //一码办成事 市场监管局人脸核身取证记录 一码申请量统计 事项名称为 营业执照发放
                            MobileUserQR mu = userService.getUserIdcard(openid);
                            if(null != mu){
                                mobileIndexService.intoUserSCJGJ(mu.getName(),mu.getIdcard(),mu.getTell());
                            }



                        }
                    }
                    String url = bindUrlNoValueQR + "?appraiseStatus=2";
                    response.sendRedirect(url);
                }
            }
        }catch (Exception e){
            log.error(openid+"法人:"+e.getMessage());
        }
    }



    /**
     * 获取人脸验证并保存 后台传材料认证 个人中心
     * openid用户微信id
     * BizToken验证码
     */
    @RequestMapping(value = "/getUserFaceResultNoValue/{openid}", method = RequestMethod.GET)
    public void getUserFaceResultNoValue(@PathVariable String openid,String BizToken, HttpServletResponse response){
        try{
            User users = UserUtils.getByLoginNameCache(openid);
            if (users != null && UserService.validatePassword(pwd, users.getPassword())) {
                if (!(JeePlusProperites.NO.equals(users.getLoginFlag()))) {
                    String token = JWTUtil.createAccessToken(openid, users.getPassword());
                    String uuid = UUID.randomUUID().toString();
                    //记录token
                    mobileLoginService.intoUserToken(uuid,token,openid);
                    //记录人脸验证
                    String result = CheckFace.GetDetectInfoText(SecretId, SecretKey, BizToken);
                    if(null != result && !"".equals(result)){
                        JSONObject obj = JSONObject.fromObject(result);
                        obj = JSONObject.fromObject(obj.get("DetectInfo"));
                        if("成功".equals(obj.getJSONObject("Text").getString("ErrMsg"))){
                            userService.intoUserCheck(openid,BizToken);
                        }
                    }
                    String url = bindUrlNoValueUser + "?uuid=" + uuid;
                    response.sendRedirect(url);
                }
            }
        }catch (Exception e){
            log.error(openid+"法人:"+e.getMessage());
        }
    }

    /**
     * 获取人脸验证并保存 后台传材料认证 首页
     * openid用户微信id
     * BizToken验证码
     */
    @RequestMapping(value = "/getIndexFaceResultNoValue/{openid}", method = RequestMethod.GET)
    public void getIndexFaceResultNoValue(@PathVariable String openid,String BizToken, HttpServletResponse response){
        try{
            User users = UserUtils.getByLoginNameCache(openid);
            if (users != null && UserService.validatePassword(pwd, users.getPassword())) {
                if (!(JeePlusProperites.NO.equals(users.getLoginFlag()))) {
                    String token = JWTUtil.createAccessToken(openid, users.getPassword());
                    String uuid = UUID.randomUUID().toString();
                    //记录token
                    mobileLoginService.intoUserToken(uuid,token,openid);
                    //记录人脸验证
                    String result = CheckFace.GetDetectInfoText(SecretId, SecretKey, BizToken);
                    if(null != result && !"".equals(result)){
                        JSONObject obj = JSONObject.fromObject(result);
                        obj = JSONObject.fromObject(obj.get("DetectInfo"));
                        if("成功".equals(obj.getJSONObject("Text").getString("ErrMsg"))){
                            userService.intoUserCheck(openid,BizToken);
                        }
                    }
                    String url = bindUrlNoValueIndex + "?uuid=" + uuid;
                    response.sendRedirect(url);
                }
            }
        }catch (Exception e){
            log.error(openid+"法人:"+e.getMessage());
        }
    }


    /**
     * 获取法人注册跳转url
     * openid用户微信id
     * BizToken验证码
     */
    @GetMapping("findPageUrl")
    public AjaxJson findPageUrl(String openid){
        return AjaxJson.success().put("data",userService.findPageUrl(openid));
    }

    /**
     * 获取人脸验证并保存
     * openid用户微信id
     * BizToken验证码
     */
    @RequestMapping(value = "/getFaceResult/{openid}", method = RequestMethod.GET)
    public void getFaceResult(@PathVariable String openid,String BizToken, HttpServletResponse response){
        Boolean qjQR = false;
        if(openid.indexOf("_qjQR") >= 0){
            qjQR = true;
            openid = openid.replace("_qjQR","");
        }
        MobileUser mu = mobileLoginService.findUserMatter(openid);
        String url = faceBindUrl+"user_id="+mu.getUserGxId()+"&BizToken="+BizToken;
        String message = HttpRequestUtil.sendGet(url,appkey);
        if(null != message){
                //String url  = faceUserUrl.replace("/id/","/"+mu.getUserGxId()+"/");
                User users = UserUtils.getByLoginNameCache(openid);
                users.setLoginFlag("1");
                users.setDelFlag("0");
                try{
                    JSONObject obj = JSONObject.fromObject(CheckFace.GetDetectInfo(SecretId, SecretKey,BizToken));
                    obj = JSONObject.fromObject(obj.getString("DetectInfo"));
                    JSONObject objImg = JSONObject.fromObject(obj.getString("IdCardData"));
                    JSONObject objUser = JSONObject.fromObject(obj.getString("Text"));
                    //mu.setOcrBack(objImg.getString("OcrBack"));
                    //mu.setOcrFront(objImg.getString("OcrFront"));
                    queueOther.toFileOcrBack(objImg.getString("OcrBack"),openid);
                    queueOther.toFileOcrFront(objImg.getString("OcrFront"),openid);
                    mu.setOcrBack("暂不下载");
                    mu.setOcrFront("暂不下载");
                    if(StringUtils.isBlank(mu.getUrl()))mu.setUrl(pageUrl);
                    mu.setIdcard(objUser.getString("OcrIdCard"));
                    mu.setAddress(objUser.getString("OcrAddress"));
                    mu.setName(objUser.getString("OcrName"));
                    mu.setLoginName(openid);
                    mu.setBizToken(BizToken);
                    int flag = mobileLoginService.updateUserMatter(mu,users);
                    if(flag <= 0){
                        log.error("保存第三方用户失败！" + mu.toString());
                    }
                    queueOther.updateUserMaterialHistory(openid);
                    if (users != null && UserService.validatePassword(pwd, users.getPassword())) {
                        if (!(JeePlusProperites.NO.equals(users.getLoginFlag()))) {
                            String token = JWTUtil.createAccessToken(openid, users.getPassword());
                            String wxurl = mu.getUrl();
                            wxurl = wxurl.replace("/wx/","/#/").replace("$$","&");
                            String uuid = UUID.randomUUID().toString();
                            mobileLoginService.intoUserToken(uuid,token,openid);
                            wxurl += "&uuid=" + uuid;
                            String loginNameOther = userService.findLoginNameOther(users.getPhone());
                            if(StringUtils.isNotBlank(loginNameOther)){
                                if(userService.delUserValue(loginNameOther,userService.findIdByLoginName(loginNameOther)) >= 1){
                                    CacheUtils.remove(loginNameOther);
                                    UserUtils.clearCache();
                                }
                            }
                            //扫码注册判断 跳转至扫码成功界面
                            if(qjQR){
                                wxurl =  bindUrlNoValueQR + "?appraiseStatus=2";
                                userService.updateQJQRStatus(openid);
                                //一码办成事 市场监管局人脸核身取证记录 一码申请量统计 事项名称为 营业执照发放
                                MobileUserQR muser = userService.getUserIdcard(openid);
                                if(null != muser){
                                    mobileIndexService.intoUserSCJGJ(muser.getName(),muser.getIdcard(),muser.getTell());
                                }
                            }
                            response.sendRedirect(wxurl);
                        }
                    }
                }catch (Exception e){
                    log.error("保存用户失败：" + e.getMessage());
                    log.error("人脸调用地址：" + url);
                    log.error("人脸核身结果：" + message);
                }
        }else{
            log.error("获取人脸信息绑定失败！" + message);
        }
    }

    /**
     * 获取所有版本号
     * @return
     */
    @RequestMapping("getVersionList")
    public AjaxJson  getVersionList(){
        return AjaxJson.success().put("data",versionService.getVersionList());

    }


    /**
     * 更新当前版本号 并更新最新事项入库
     * version更新版本号
     * @return
     */
    @RequestMapping("updateCacheVersion")
    public AjaxJson  updateCacheVersion(String version){
        versionService.updateYmbcsMatter(versionService.getVersion(),version);
        versionService.updateCacheVersion(version);
        return AjaxJson.success("操作成功！");
    }

    /**
     * 获得当前版本号
     * @return
     */
    @RequestMapping("getVersion")
    public AjaxJson  getVersion(){
        return AjaxJson.success().put("data",versionService.getVersion());

    }

    /**
     * 获取用户基础信息
     * @return
     */
    @GetMapping("getUser")
    public AjaxJson  getUser(){
        Map<String,String> map = mobileLoginService.findUser(UserUtils.getUser().getLoginName());
        String tell = null;
        if(map.containsKey("tell"))tell = map.get("tell");
        if(null != tell && tell.length() == 11){
            map.put("tell",tell.substring(0,3)+"*****"+tell.substring(tell.length()-3,tell.length()));
        }
        return AjaxJson.success("操作成功！").put("data",map);
    }

    /**
     * 获取微信基础配置
     * WXUrl当前路径
     * @return
     */
    @GetMapping("getConfig")
    public AjaxJson getConfig(String WXUrl){
        return AjaxJson.success("操作成功！").put("data",weixinUtil.getWebConfigInfo(WXUrl,AppID));
    }

    /**
     * 获取点位名称
     * areaId点位标识
     * @return
     */
    @GetMapping("getAreaName")
    public AjaxJson getAreaName(String areaId){
        return AjaxJson.success("操作成功！").put("areaName",mobilebusinessService.getAreaName(areaId));
    }

    /**
     * 获取群众历史未注册成功数据
     * userId用户id
     * @return
     */
    @GetMapping("getUserHistory")
    public AjaxJson getUserHistory(String userId) throws UnsupportedEncodingException {
        User us = UserUtils.getByLoginNameCache(userId);
        if(us == null){
            return AjaxJson.error("user is null");
        }
        return AjaxJson.success("操作成功！").put("name",us.getName()).put("tell", Base64.encodeBase64String(us.getPhone().getBytes("utf-8"))).put("address",us.getAddress());
    }

    /**
     * 获取法人历史未注册成功数据
     * userId用户id
     * @return
     */
    @GetMapping("findLegalValue")
    public AjaxJson findLegalValue(String openid) throws UnsupportedEncodingException {
        return AjaxJson.success("操作成功！").put("data", Base64.encodeBase64String(JSONObject.fromObject(mobileLoginService.findLegalValue(openid)).toString().getBytes("utf-8")));
    }

    /**
     * 获取群众登录token
     * userId用户id
     * @return
     */
    @GetMapping("getUserToken")
    public AjaxJson getUserToken(String uuid){
        return AjaxJson.success("操作成功！").put("token",mobileLoginService.getTokenById(uuid));
    }
    /**
     * 获取群众登录token 对接卓繁
     * userId用户id
     * @return
     */
    @GetMapping("getUserTokenById")
    public AjaxJson getUserTokenById(@RequestHeader("AppKey") String AppKey,String uuid){
        if (!AppKeyValue.equals(AppKey)) return AjaxJson.error("AppKey is error!").put("code", 400);
        return AjaxJson.success("操作成功！").put("token",mobileLoginService.getTokenById(uuid));
    }



    /**
     * 添加群高馨办访问统计
     * userId用户id
     * intoUserCount
     * @return
     */
    @GetMapping("intoUserCount")
    public void intoUserCount(){
        mobileLoginService.intoUserCount(DateUtils.getDate());
    }

    /**
     * 添加群众一码办成事访问统计
     * userId用户id
     * intoUserCount
     * @return
     */
    @GetMapping("intoYmbcsCount")
    public void intoYmbcsCount(){
        mobileLoginService.intoYmbcsCount(DateUtils.getDate());
    }

    /**第三方
     * 验证并保存用户信息
     * openid用户微信id
     * tell联系电话
     * username用户昵称
     * address地址
     * 跳转url
     */
    @PostMapping("saveOtherUserInfo")
    public AjaxJson saveOtherUserInfo(String name,String openid, String tell, String username,String address,String idcard,String gxOtherId,String headimgurl,String areaName) {
        if(StringUtils.isBlank(name) || StringUtils.isBlank(openid) || StringUtils.isBlank(tell) || StringUtils.isBlank(username) || StringUtils.isBlank(address) || StringUtils.isBlank(idcard) || StringUtils.isBlank(gxOtherId)){
            return AjaxJson.error("参数不完整！").put("code",400);
        }else{
            User users = new User();
            Office of = new Office();
            List<String> roleIdList = new ArrayList<String>();
            roleIdList.add(roleId);
            of.setId(officeId);
            of.setName(officeName);
            Office company = new Office();
            company.setId(companyId);
            company.setName(companyName);
            users.setPassword(pwd);
            users.setLoginFlag("1");
            users.setDelFlag("0");
            users.setOffice(of);
            users.setCompany(company);
            users.setPhone(tell);
            users.setRoleIdList(roleIdList);
            if(StringUtils.isBlank(headimgurl)){
                headimgurl = userImg;
            }
            //注册
            users.setNo("0000");
            users.setPassword(userService.entryptPassword(users.getPassword()));
            users.setName(name);
            users.setAddress(address);
            users.setLoginName(openid);
            users.setPhoto(headimgurl);
            // 角色数据有效性验证，过滤不在授权内的角色
            List<Role> roleList = Lists.newArrayList();
            for (String roleId : roleIdList) {
                roleList.add(roleService.get(roleId));
            }
            users.setRoleList(roleList);
            // 保存用户信息
            try {
                mobileLoginService.intoOtherAllValue(gxOtherId,idcard,username,address,openid,tell,areaName);
                userService.saveUser(users);
                return AjaxJson.success("注册成功！");
            }catch (Exception e){
                return AjaxJson.error("注册失败！").put("code",400);
            }
        }
    }

    @PostMapping("savelegalUser")
    public AjaxJson savelegalUser(String vcode,String companyName,String socialCode,String legalName,String idcard,String tell,String openid,String pageUrl) {
        tell = new String(Base64.decodeBase64(tell));
        socialCode = new String(Base64.decodeBase64(socialCode));
        if(StringUtils.isNotBlank(idcard)){
            idcard = new String(Base64.decodeBase64(idcard));
        }
        String cache_key = openid + "-" + tell;
        Object cacheInfo = CacheUtils.get(VERIFICATION_CODE_CACHE, cache_key);
        if (null == cacheInfo) {
            return AjaxJson.error("验证失效！");
        } else {
            if (cacheInfo.toString().equalsIgnoreCase(vcode)) {
                if(userService.findlegalUser(socialCode,openid) <= 0){
                    if(userService.intolegalUser(legalName,companyName,socialCode,idcard,tell,openid,pageUrl) >= 1){
                        //填写基本数据
                        synchronized (this){
                            User users = UserUtils.getByLoginNameNow(openid);
                            if(users != null && openid.equals(users.getLoginName())){
                                return AjaxJson.error("该微信已绑定用户！");
                            }else{
                                users = UserUtils.getByLoginNameCache(openid);
                                if(users == null){
                                    users = new User();
                                }
                                Office of = new Office();
                                List<String> roleIdList = new ArrayList<String>();
                                roleIdList.add(roleId);
                                of.setId(officeId);
                                of.setName(officeName);
                                Office company = new Office();
                                company.setId(companyId);
                                company.setName(companyName);
                                users.setPassword(pwd);
                                //禁止登录
                                users.setLoginFlag("0");
                                //无效
                                users.setDelFlag("1");
                                users.setOffice(of);
                                users.setCompany(company);
                                users.setPhone(tell);
                                users.setRoleIdList(roleIdList);
                                //获取微信用户信息
                                String wxToken = String.valueOf(CacheUtils.get(TOKEN_CACHE, "token"));
                                String urls = WeiXinConfig.weixin_user_info.replace("OPENID", openid).replace("ACCESS_TOKEN", wxToken);
                                String headimgurl = "";
                                JSONObject jsonUser = null;
                                try {
                                    jsonUser = JSONObject.fromObject(HttpRequestUtil.sendPost(urls, null));
                                    if(jsonUser != null && null != jsonUser.get("headimgurl")){
                                        headimgurl = jsonUser.getString("headimgurl");
                                        headimgurl = headimgurl.replace("http","https");
                                    }else{
                                        headimgurl = userImg;
                                    }
                                }catch (Exception e){
                                    headimgurl = userImg;
                                    log.error(e.getMessage());
                                    e.printStackTrace();
                                }
                                //注册
                                users.setNo("0000");
                                users.setPassword(userService.entryptPassword(users.getPassword()));
                                users.setName(legalName);
                                users.setAddress("");
                                users.setLoginName(openid);
                                users.setPhoto(headimgurl);
                                // 角色数据有效性验证，过滤不在授权内的角色
                                List<Role> roleList = Lists.newArrayList();
                                for (String roleId : roleIdList) {
                                    roleList.add(roleService.get(roleId));
                                }
                                users.setRoleList(roleList);
                                // 保存用户信息
                                userService.saveUser(users);
                                userService.saveUserOther(openid,"",tell,pageUrl);
                                return AjaxJson.success("提交成功！");
                            }
                        }
                    }else{
                        return AjaxJson.error("添加异常");
                    }
                }else{
                    return AjaxJson.error("该组织代码或微信号已绑定");
                }
            }else{
                return AjaxJson.error("验证码错误！");
            }
        }
    }

    @PostMapping("savelegalUserRZ")
    public AjaxJson savelegalUserRZ(String vcode,String companyName,String socialCode,String legalName,String idcard,String tell,String openid,String pageUrl) {
        tell = new String(Base64.decodeBase64(tell));
        socialCode = new String(Base64.decodeBase64(socialCode));
        if(StringUtils.isNotBlank(idcard)){
            idcard = new String(Base64.decodeBase64(idcard));
        }
        String cache_key = openid + "-" + tell;
        Object cacheInfo = CacheUtils.get(VERIFICATION_CODE_CACHE, cache_key);
        if (null == cacheInfo) {
            return AjaxJson.error("验证失效！");
        } else {
            if (cacheInfo.toString().equalsIgnoreCase(vcode)) {
                if(userService.findlegalUser(socialCode,openid) <= 0){
                    if(userService.intolegalUser(legalName,companyName,socialCode,idcard,tell,openid,pageUrl) >= 1){
                        return AjaxJson.success("提交成功！");
                    }else{
                        return AjaxJson.error("添加异常");
                    }
                }else{
                    return AjaxJson.error("该组织代码已绑定");
                }
            }else{
                return AjaxJson.error("验证码错误！");
            }
        }
    }

    public Map<String,String> jieMiRYB(String userName,String idCard,String tel,String jwtToken,String uuid,String type,String isRYB,String deptName,String deptCode,String socialCreditCode){
        Map<String,String> map=new HashMap<>();
        if("20".equals(type)){
            try {
                map.put("userName",new String(RSAUtils.decryptByPrivateKey(RSAUtils.decryptBASE64(userName), TFRYB_KEY),"utf-8"));
                map.put("idCard",new String(RSAUtils.decryptByPrivateKey(RSAUtils.decryptBASE64(idCard), TFRYB_KEY)));
                map.put("tel",new String(RSAUtils.decryptByPrivateKey(RSAUtils.decryptBASE64(tel), TFRYB_KEY)));
            } catch (Exception e) {
                e.printStackTrace();
            }
            map.put("jwtToken",jwtToken);
            map.put("uuid",uuid);
            map.put("type",type);
            map.put("isRYB",isRYB);

        }else{
            try {
                map.put("userName",new String(RSAUtils.decryptByPrivateKey(RSAUtils.decryptBASE64(userName), TFRYB_KEY),"utf-8"));
                map.put("tel",new String(RSAUtils.decryptByPrivateKey(RSAUtils.decryptBASE64(tel), TFRYB_KEY)));

            } catch (Exception e) {
                e.printStackTrace();
            }

            map.put("idCard",idCard);
            map.put("jwtToken",jwtToken);
            map.put("uuid",uuid);
            map.put("type",type);
            map.put("isRYB",isRYB);
            map.put("deptName",deptName);
            map.put("deptCode",deptCode);
            map.put("socialCreditCode",socialCreditCode);
        }

        return map;
    }
    public Map<String,String> jieMiTFTB(String userName,String idCard,String tel,String jwtToken,String uuid,String type,String isRYB,String deptName,String deptCode,String socialCreditCode){
        Map<String,String> map=new HashMap<>();
        if("20".equals(type)){
            try {
                map.put("userName",new String(RSAUtils.decryptByPrivateKey(RSAUtils.decryptBASE64(userName), TFTB_KEY),"utf-8"));
                map.put("idCard",new String(RSAUtils.decryptByPrivateKey(RSAUtils.decryptBASE64(idCard), TFTB_KEY)));

            } catch (Exception e) {
                e.printStackTrace();
            }
            map.put("tel",tel);
            map.put("uuid",uuid);
            map.put("type",type);
            map.put("isRYB",isRYB);

        }else{
            try {
                map.put("userName",new String(RSAUtils.decryptByPrivateKey(RSAUtils.decryptBASE64(userName), TFTB_KEY),"utf-8"));
            } catch (Exception e) {
                e.printStackTrace();
            }
            map.put("tel",tel);
            map.put("idCard",idCard);
            map.put("uuid",uuid);
            map.put("type",type);
            map.put("isRYB",isRYB);
            map.put("deptName",deptName);
            map.put("deptCode",deptCode);
            map.put("socialCreditCode",socialCreditCode);

        }

        return map;
    }

    //人才code获取
    @GetMapping(value ="getRCCode")
    public AjaxJson getRCCode(){
        return AjaxJson.success().put("data",HttpRequestUtil.getRCCode(rcCodeUrl));
    }

    public static String sendJsonByGetReq(String url, String param, String encoding,String appkey) throws Exception {
        String body = "";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGetWithEntity httpGetWithEntity = new HttpGetWithEntity(url,appkey);
        HttpEntity httpEntity = new StringEntity(param, ContentType.APPLICATION_JSON);
        httpGetWithEntity.setEntity(httpEntity);
        //执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = client.execute(httpGetWithEntity);
        //获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, encoding);
        }
        //释放链接
        response.close();
        return body;
    }
}

